package com.dabaozhan.modules.wx_app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.ImageOperation;
import com.dabaozhan.common.utils.UploadFile;
import com.dabaozhan.common.utils.aliyun.ocr.CardUtils;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.entity.CardEntity;
import com.dabaozhan.modules.wx_app.entity.SiteIndustryEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.service.CardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * @author houzhong
 * @date 2019-01-14 11:56
 */
@Api(value = "身份证上传", description = "身份证上传")
@RestController
@RequestMapping("/wx_app")
public class CardController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CardController.class);

    /**身份证*/
    @Autowired
    private CardService cardService;

    @ApiOperation(value = "上传身份证信息")
    @RequestMapping("/uploadCardFile")
    public String uploadCardFile(@RequestParam(value = "file", required = false) MultipartFile[] file, HttpServletRequest request) {
        ResponseDto<CardEntity> responseDto = new ResponseDto<CardEntity>();
        try {
            request.setCharacterEncoding("UTF-8");
            //用户id
            String userId = request.getParameter("userId");
            //图片保存路径
            String pathUrl = request.getSession().getServletContext().getRealPath("/")+ ("fileImage/");

            JSONObject jsonObject = UploadFile.uploadFileImg(file,pathUrl);
            LOGGER.info("解析营业执照数据{}",JSON.toJSONString(jsonObject));

            //图片名称
            String targetFileName = jsonObject.getString("targetFileName");
            //解析身份证信息
            JSONObject res_obj = CardUtils.getCard(pathUrl + targetFileName);

            if (res_obj != null) {
                System.out.println("校验成功------");
                //解析身份证
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject dataValueObj = JSON.parseObject(output);

                //身份征号
                String cardNum = dataValueObj.getString("num");
                //地址
                String cardAddress = dataValueObj.getString("address");
                //性别
                String cardSex = dataValueObj.getString("sex");
                //姓名
                String cardName = dataValueObj.getString("name");
                //生日
                String cardBirth = dataValueObj.getString("birth");

                CardEntity card = new CardEntity();
                card.setCardNum(cardNum);
                card.setCardAddress(cardAddress);
                card.setCardSex(cardSex);
                card.setCardName(cardName);
                card.setCardBirth(cardBirth);
                card.setCardUrl(pathUrl + targetFileName);
                card.setUserId(userId);

                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(card);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_303);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("上传身份证信息发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("上传身份证信发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "保存和修改身份证信息")
    @RequestMapping("/saveCard")
    public String saveCard(CardEntity v,HttpServletRequest request) {
        ResponseDto<CardEntity> responseDto = new ResponseDto<CardEntity>();
        //图片保存路径
        String pathUrl = request.getSession().getServletContext().getRealPath("/")+ ("fileImage/");
        //获取文件目录图片 并保存到七牛
        String url = ImageOperation.encodeImage(v.getCardUrl().substring(v.getCardUrl().lastIndexOf("/") + 1), pathUrl);

        try {
            //查询属否存在
            CardEntity card = cardService.findByCardUserId(v.getUserId());
            if (card != null) {
                card.setCardNum(v.getCardNum());
                card.setCardSex(v.getCardSex());
                card.setCardName(v.getCardName());
                card.setCardBirth(v.getCardBirth());
                card.setCardAddress(card.getCardAddress());
                card.setCardUrl(v.getCardUrl());
                cardService.updateCard(card);

                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(card);
            }else {
                v.setCardUrl(url);
                cardService.saveCard(v);

                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(v);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("保存和修改身份证信息信息:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("保存和修改身份证信息发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }
}
